<template>
    <div class="lar-table">
        <!--{{fullApi}}-->
        <!--搜索盒子-->
        <!--<lar-ui-tab></lar-ui-tab>-->
        <!--按钮组-->
        <el-row :gutter="24">
            <el-col :span="24" style="background-color: #fff">
                <transition name="fade">
                    <lar-search-box :model="model" :schemas="searchSchemas" :advSchemas="advSchemas" :pipeName="pipeName">
                        <template slot="search">
                            <!--<el-button-group class="table&#45;&#45;button-group">-->
                            <!--<el-button  size="small" @click="add()" v-for="" class="simple-button" plain icon="el-icon-plus">-->
                            <!--<div>添加</div>-->
                            <!--</el-button>-->
                            <!--<el-button  size="small" @click="showSearch=!showSearch" class="simple-button" icon="el-icon-search">-->
                            <!--<div>搜索</div>-->
                            <!--</el-button>-->
                            <!--{{btns}}-->
                            <el-button size="mini" type="primary" v-for="btn in btns" :key="btn.html" @click="handelButton(btn)" :icon="btn.icon">
                                {{btn.html}}
                            </el-button>
                            <slot name="orderSearchBu"></slot>
                            <el-button @click="getData()" size="mini" type="primary" icon="el-icon-refresh">刷新
                            </el-button>
                            <el-button @click="delMultiRows()" size="mini" type="danger" icon="el-icon-delete" v-if="canDel">
                                删除
                            </el-button>
                            <!--</el-button-group>-->
                        </template>
                    </lar-search-box>
                </transition>
                &nbsp;
            </el-col>
        </el-row>
        <!--数据表单-->

        <!--当前运单scope-->
        <slot name="nowOrder"></slot>
        <!--当前运单scope-->
        <!--运单调度scope-->
        <slot name="dispatchOrder"></slot>
        <slot name="dispatchMap" :data="{tableSelect:multipleSelection}"></slot>
        <!--运单调度scope-->
        <!--调度预警-->
        <slot name="dispatchWarning" :data="{tableSelect: multipleSelection,totalNum: pageInfo.total}"></slot>
        <!--调度预警-->
        <!--运单搜索-->
        <slot name="orderSearch" :data="{totalNum: pageInfo.total}"></slot>
        <!--运单搜索-->
        <!--地址异常预警-->
        <slot name="addressWarning" :data="{totalNum: pageInfo.total}"></slot>
        <!--地址异常预警-->
        <el-table
                :data="tableData"
                v-loading="loading"
                :border="true"
                highlight-current-row
                :show-overflow-tooltip="true"
                @selection-change="handleSelectionChange"
                @sort-change="handleSort"
                :header-cell-style="tableHeaderColor"
                style="width: 100%;">
            <!--id的列-->
            <el-table-column type="expand" width="60" v-if="Schemas.show&&Schemas.show.is_drop.default == '1'">
                <template slot-scope="props">
                    <slot :name="Schemas.show.is_drop.action" :data="{data:props}"></slot>
                </template>
            </el-table-column>
            <el-table-column
                    v-if="Schemas.show&&Schemas.show.is_show.default == '1'"
                    :sort-change="handleSort"
                    type="selection"
                    align="center"
                    width="36">
            </el-table-column>
            <!--数据的列-->
            <!--sortable-->
            <el-table-column
                    v-for="schema in Schemas.component_fields"
                    :key="schema.key"
                    sortable
                    :prop="schema.key"
                    :label="schema.name"
                    :min-width="schema.width ">
                <template slot-scope="scope">
                    <lar-table-ceil
                            v-if="schema"
                            :data="scope.row"
                            :schema="schema"
                            :action="'table'"
                            @quick-change="quickChange($event,schema.key,scope.row)">
                    </lar-table-ceil>
                </template>
            </el-table-column>
            <!--操作的列-->
            <el-table-column
                    class-name="action-th"
                    header-align="center"
                    label="管理"
                    fixed="right"
                    v-if="Schemas.config"
                    width="100">
                <!--:width="Object.keys(Schemas.config.action).length*76"-->
                <template slot-scope="scope">
                    <div style="text-align: center">
                        <span v-for="action in Schemas.config.action" :key="action.name">
                          <el-tooltip class="item" effect="dark" :content="action.html" placement="top">
                            <el-button :type="action.type"
                                       style="transform: scale(0.8);zoom: 0.99"
                                       circle
                                       @click="handleAction(scope.$index, scope.row, action)">
                                {{action.html.substring(0,1)}}
                            </el-button>
                          </el-tooltip>
                    </span>
                    </div>
                    <div>
                        <!--<el-dropdown >-->
                        <!--<el-button round size="mini" type="primary">-->
                        <!--操作<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
                        <!--</el-button>-->
                        <!--<el-dropdown-menu slot="dropdown">-->

                        <!--<el-dropdown-item-->
                        <!--v-for="action in Schemas.config.action"-->
                        <!--:key="action.name"-->
                        <!--&gt;-->
                        <!--<div style="height: 100%;width: 100%;" @click="handleAction(scope.$index, scope.row, action)">{{action.html}}</div>-->
                        <!--</el-dropdown-item>-->
                        <!--</el-dropdown-menu>-->
                        <!--</el-dropdown>-->
                        <!--<el-button-->
                        <!--style="text-align: right"-->
                        <!--v-for="action in Schemas.config.action"-->
                        <!--:key="action.name"-->
                        <!--round-->
                        <!--size="mini"-->
                        <!--:type="action.type"-->
                        <!--@click="handleAction(scope.$index, scope.row,action)">-->
                        <!--{{action.html}}-->
                        <!--</el-button>-->
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div v-if="pageInfo.path" class="block" style="text-align: right;padding-bottom: 20px">
            <br/>
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageInfo.current_page"
                    :page-sizes="[10, 20, 40, 60, 80]"
                    :page-size="pageInfo.per_page"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageInfo.total">
            </el-pagination>
        </div>
    </div>

</template>
<script>
    import Vue from 'vue'

    export default {
        props: {
            model: {
                type: String,
            },
            action: {
                type: String,
                default: 'base.table',
            }
        },
        data() {
            return {
                isShowCheck: true,
                isShowDrop: true,
                title: '',
                tableData: [],
                multipleSelection: [],
                api: '',
                zeroing: true,
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1,
                },
                btns: [],
                apiQuery: {},//查询的参数
                Schemas: [],
                showSearch: true,
                loading: true,
                searchQueryCache: {
                    data: {},
                    time: 0,
                },
                canQuickChange: false,//是否全部加载完成了
            }
        },

        mounted: function () {
            this.getSchemas();
        },
        computed: {
            canDel() {
                if (this.Schemas.config && this.Schemas.config.action.del) {
                    return true;
                }
                return false;
            },
            dataRefreshEvents() {
                return this.$store.getters.getRefreshEvents(this.model);
            },
            dataRefreshDialog() {
                return this.$store.state.num;
            },
            searchQuery() {
                this.zeroing = true;
                let data = this.$store.getters.getPipe(this.pipeName);
                return this.$larfree.getSearchQuery(data);

            },
            pipeName() {
                return this.Schemas.pipeName ? this.Schemas.pipeName : this.model + '.table';
            },
            searchSchemas: function () {
                if (!this.Schemas)
                    return [];
                return this.Schemas['search'];
            },
            advSchemas: function () {
                if (!this.Schemas || !this.Schemas['adv_search'])
                    return [];
                return this.Schemas['adv_search'];
            },
            fullApi: function () {
                if (!this.api)
                    return '';
                let query = this.apiQuery;
                query['pageSize'] = this.pageInfo.per_page * 1;
                query['page'] = this.pageInfo.current_page;

                query = Object.assign(query, this.searchQuery);
                return this.$larfree.httpQuery(query, this.api);
            },
        },

        watch: {
            model: function () {
                this.getSchemas();
            },
            dataRefreshEvents: function () {
                this.loading = true;
                this.getData();
            },
            dataRefreshDialog: function () {
                this.loading = true;
                this.getData();
            },
            //如果api变化就请求数据
            fullApi: function () {
                this.loading = true;
                this.getData();
            }
        },

        methods: {
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            },
            handelButton(event) {
                if (event.action == 'add') {
                    this.add();
                }
                this.$emit('handelButton', event, this.multipleSelection);
            },
            //获取配置
            getSchemas() {
                if (!this.model)
                    return '';
                this.loading = true;
                this.$http.get('/system/component/' + this.model + '/' + this.action, {ttl: 3600})
                    .then((response) => {
                        this.loading = false;
                        if (response.data.status == 1) {
                            this.Schemas = response.data.data;
                            this.api = response.data.data.config.api;
                            this.btns = response.data.data.config.button;
                            this.tableData = [];
                        } else {
                            this.$message.error('Table模块错误');
                        }
                    })
                    .catch((error) => {
                        this.loading = false;
                        this.$message.error('Table模块请求错误');
                        console.log(error);
                    });
            },
            //渲染操作列
            // actionRender(h){
            //     //如果有操作权限
            //     if(this.Schemas.config.button.add)
            //         return <span>操作<span class="add_button"  onClick={this.add}>
            //                     <span>
            //                         <i class="el-icon-plus"></i>
            //                     </span>
            //                 </span></span>;
            //     else
            //         return <span>操作</span>;
            // },
            //处理下action的触发时间
            handleAction(index, data, action) {
                // this.$debug.log(action);
                if (action.url) {
                    let url = this.$larfree.replaceParm(action.url, data);
                    this.$debug.log(url, 'actionUrl', this);
                    this.$router.push({path: url})
                } else if (action.action) {
                    let func = this.$larfree.replaceParm(action.action, data);
                    action.real_api = this.$larfree.replaceParm(action.api, data);
                    this[func](index, data, action);
                }
            },

            //第一列选中
            handleSelectionChange(val) {
                this.multipleSelection = val;
                this.$emit('SelectionChange', val);
            },
            handleSizeChange(val) {
                this.pageInfo.per_page = val;
            },
            handleCurrentChange(val) {
                this.zeroing = false;
                this.pageInfo.current_page = val;
            },
            handleSort(column) {
                let sort = 'desc';
                if (column.order == 'ascending')
                    sort = 'asc';
                Vue.set(this.apiQuery, '@sort', column.column.property + '.' + sort);
            },
            //批量删除
            delMultiRows() {
                this.$confirm('是否删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //读取操作按钮中的删除操作 如果没有 说明不能删除
                    let delAction = this.Schemas.config.action.filter((item) => {
                        if (item.action == 'delRows')
                            return item;
                    })
                    if (delAction.length < 1) {
                        this.$message.error('无权删除');
                        return false;
                    }
                    delAction = delAction[0];
                    this.multipleSelection.forEach((item) => {
                        let api = this.$larfree.replaceParm(delAction.api, item);
                        this.$http.delete(api).then((response) => {
                            if (response.data.status == 1) {
                                this.getData();
                            } else {
                                this.$message.error(response.data.msg);
                            }
                        }).catch(() => {
                            this.$message.error('删除失败:网络错误');
                        })
                    })
                }).catch(() => {

                });
            },
            //直接删除
            delRows(index, data, action) {
                this.$confirm('是否删除' + data.id + '?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((data) => {
                    console.log(data);
                    this.$http.delete(action.real_api).then((response) => {
                        if (response.data.status == 1) {
                            this.getData();
                        } else {
                            this.$message.error(response.data.msg);
                        }
                    }).catch(() => {
                        this.$message.error('删除失败:网络错误');
                    })
                }).catch(() => {
                    //取消
                });
            },
            //添加
            add() {
                this.$router.push({path: this.Schemas.config.button.add.url})
            },
            //获取数据
            getData() {
                this.loading = true;
                this.canQuickChange = false;
                if (this.zeroing) {
                    this.pageInfo.current_page = 1;
                }
                console.log(this.fullApi, 'api');
                if (!this.fullApi) {
                    return false;
                }
                this.$http.get(this.fullApi)
                    .then((response) => {
                        this.loading = false;
//                    this.debug.log(response.data.data,this.api);
                        this.tableData = response.data.data;
                        if (response.data.meta)
                            this.pageInfo = response.data.meta;

                        //让他全部加载完了才能开始
                        setTimeout(() => {
                            this.canQuickChange = true;
                        }, 2000);
                        this.zeroing = false;
                    })
                    .catch((error) => {
                        console.log('table.vue', error);
                        this.$message.error('Table模块请求数据错误');
                    });

            },

            /**
             * 快速修改
             * @param $event
             * @param key
             * @param data
             */
            quickChange($event, key, data) {

                if (this.canQuickChange) {
                    let newValue = $event;
                    // this.$debug.log(this.Schemas);
                    let url = this.$larfree.replaceParm(this.Schemas.config.quick_change_api, data);
                    let putData = {};
                    putData[key] = newValue;
                    this.$http.put(url, putData)
                        .then((response) => {
                            if (response.data.status == 1) {
                                this.$message.success(response.data.msg);
                            } else {
                                this.$message.error(response.data.msg);
                            }
                        });
                }
            },
        }
    }
</script>
<style lang="less">
    .lar-table {
        .el-range-editor.el-input__inner {
            padding: 0px 10px !important;
        }
        .el-input__inner {
            height: 32px !important;
            line-height: 32px !important;
        }
        .el-date-editor .el-range-input,
        .el-date-editor .el-range-separator {
            height: auto !important;
        }
    }

    .el-table {
        font-size: 12px !important;
    }

    .el-table--border, .el-table--group {
        border: none;
    }

    .el-table--border::after, .el-table--group::after {
        width: 0px !important;
    }

    .lar-table .el-table--border td, .lar-table .el-table--border th {
        border-right: none;
    }

    /*.action-th .cell {*/
    /*padding: 0;*/
    /*}*/
    .add_button span {
        font-size: 24px;
        background: #ec407a;
        color: white;
        line-height: 46px;
        width: 44px;
        height: 44px;
        top: -12px;
        position: absolute;
        text-align: center;
        border-radius: 30px;
        cursor: pointer;
        box-shadow: 0 0 7px #aaa;
        z-index: 99;
        margin-left: 10px;
        transform: rotate(0deg);
        transition: box-shadow, transform 2s;

    }

    .add_button span:hover {
        transform: rotate(360deg);
        box-shadow: 0 0 10px #888888;
        transition: box-shadow, transform 2s;
    }

    .el-table .cell, .el-table th div {
        overflow: initial !important;
    }

    .el-button.is-circle {
        padding: 6px;
    }

    .table--button-group div {
        font-size: 10px;
    }

    @media screen and (max-width: 1400px) {
        .table--button-group .el-button {
            font-size: 14px;
            padding: 0px 4px;

        }

        .table--button-group button {
            font-size: 24px !important;
        }
    }
</style>
